<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Setting, 
  Monitor, 
  Bell, 
  Lock, 
  Moon, 
  Sunny, 
  Refresh,
  Download,
  Upload,
  Delete,
  Check
} from '@element-plus/icons-vue'

// 系统设置数据
const settings = reactive({
  // 主题设置
  theme: {
    mode: 'light', // light, dark, auto
    primaryColor: '#409EFF',
    borderRadius: 'medium', // small, medium, large
    compactMode: false
  },
  
  // 通知设置
  notifications: {
    enableDesktop: true,
    enableEmail: true,
    enableSMS: false,
    quietHours: {
      enabled: false,
      start: '22:00',
      end: '08:00'
    },
    types: {
      system: true,
      security: true,
      updates: false,
      marketing: false
    }
  },
  
  // 安全设置
  security: {
    autoLogout: true,
    autoLogoutTime: 30, // 分钟
    twoFactorAuth: false,
    loginNotification: true,
    passwordExpiry: false,
    passwordExpiryDays: 90
  },
  
  // 系统偏好
  preferences: {
    language: 'zh-CN',
    timezone: 'Asia/Shanghai',
    dateFormat: 'YYYY-MM-DD',
    timeFormat: '24h',
    pageSize: 20
  },
  
  // 数据管理
  data: {
    autoBackup: true,
    backupFrequency: 'daily', // daily, weekly, monthly
    retentionDays: 30,
    exportFormat: 'json'
  }
})

// 主题色选项
const themeColors = [
  { name: '默认蓝', value: '#409EFF' },
  { name: '成功绿', value: '#67C23A' },
  { name: '警告橙', value: '#E6A23C' },
  { name: '危险红', value: '#F56C6C' },
  { name: '信息灰', value: '#909399' },
  { name: '紫色', value: '#722ED1' },
  { name: '青色', value: '#13C2C2' },
  { name: '粉色', value: '#EB2F96' }
]

// 语言选项
const languageOptions = [
  { label: '简体中文', value: 'zh-CN' },
  { label: 'English', value: 'en-US' },
  { label: '繁體中文', value: 'zh-TW' },
  { label: '日本語', value: 'ja-JP' }
]

// 时区选项
const timezoneOptions = [
  { label: '北京时间 (UTC+8)', value: 'Asia/Shanghai' },
  { label: '东京时间 (UTC+9)', value: 'Asia/Tokyo' },
  { label: '纽约时间 (UTC-5)', value: 'America/New_York' },
  { label: '伦敦时间 (UTC+0)', value: 'Europe/London' }
]

// 加载状态
const loading = ref(false)
const backupLoading = ref(false)
const exportLoading = ref(false)
const importLoading = ref(false)

// 保存设置
const saveSettings = async () => {
  try {
    loading.value = true
    
    // 这里应该调用API保存设置
    // await api.saveSettings(settings)
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('设置保存成功')
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败，请重试')
  } finally {
    loading.value = false
  }
}

// 重置设置
const resetSettings = async () => {
  try {
    await ElMessageBox.confirm(
      '此操作将重置所有设置到默认值，是否继续？',
      '重置设置',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 重置为默认值
    Object.assign(settings.theme, {
      mode: 'light',
      primaryColor: '#409EFF',
      borderRadius: 'medium',
      compactMode: false
    })
    
    ElMessage.success('设置已重置')
  } catch {
    // 用户取消
  }
}

// 备份数据
const backupData = async () => {
  try {
    backupLoading.value = true
    
    // 模拟备份过程
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    ElMessage.success('数据备份成功')
  } catch (error) {
    ElMessage.error('备份失败，请重试')
  } finally {
    backupLoading.value = false
  }
}

// 导出设置
const exportSettings = async () => {
  try {
    exportLoading.value = true
    
    // 模拟导出
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    const dataStr = JSON.stringify(settings, null, 2)
    const dataBlob = new Blob([dataStr], { type: 'application/json' })
    const url = URL.createObjectURL(dataBlob)
    
    const link = document.createElement('a')
    link.href = url
    link.download = `settings-${new Date().getTime()}.json`
    link.click()
    
    URL.revokeObjectURL(url)
    ElMessage.success('设置导出成功')
  } catch (error) {
    ElMessage.error('导出失败，请重试')
  } finally {
    exportLoading.value = false
  }
}

// 清除缓存
const clearCache = async () => {
  try {
    await ElMessageBox.confirm(
      '此操作将清除所有缓存数据，是否继续？',
      '清除缓存',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 清除缓存逻辑
    localStorage.clear()
    sessionStorage.clear()
    
    ElMessage.success('缓存清除成功')
  } catch {
    // 用户取消
  }
}

// 初始化设置
onMounted(() => {
  // 从本地存储或API加载设置
  const savedSettings = localStorage.getItem('systemSettings')
  if (savedSettings) {
    try {
      Object.assign(settings, JSON.parse(savedSettings))
    } catch (error) {
      console.error('加载设置失败:', error)
    }
  }
})
</script>

<template>
  <div class="settings-container">
    <div class="settings-header">
      <h1>系统设置</h1>
      <p>管理您的系统偏好和应用配置</p>
    </div>

    <el-row :gutter="24">
      <el-col :lg="16" :md="24">
        <div class="settings-content">
          <!-- 主题设置 -->
          <el-card class="settings-card">
            <template #header>
              <div class="card-header">
                <el-icon><Monitor /></el-icon>
                <span>主题设置</span>
              </div>
            </template>
            
            <el-form label-width="120px">
              <el-form-item label="主题模式">
                <el-radio-group v-model="settings.theme.mode">
                  <el-radio-button value="light">
                    <el-icon><Sunny /></el-icon>
                    浅色
                  </el-radio-button>
                  <el-radio-button value="dark">
                    <el-icon><Moon /></el-icon>
                    深色
                  </el-radio-button>
                  <el-radio-button value="auto">
                    <el-icon><Monitor /></el-icon>
                    自动
                  </el-radio-button>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="主题色">
                <div class="color-picker-group">
                  <div
                    v-for="color in themeColors"
                    :key="color.value"
                    class="color-option"
                    :class="{ active: settings.theme.primaryColor === color.value }"
                    :style="{ backgroundColor: color.value }"
                    @click="settings.theme.primaryColor = color.value"
                  >
                    <el-icon v-if="settings.theme.primaryColor === color.value">
                      <Check />
                    </el-icon>
                  </div>
                </div>
              </el-form-item>

              <el-form-item label="圆角大小">
                <el-radio-group v-model="settings.theme.borderRadius">
                  <el-radio value="small">小</el-radio>
                  <el-radio value="medium">中</el-radio>
                  <el-radio value="large">大</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="紧凑模式">
                <el-switch v-model="settings.theme.compactMode" />
                <span class="form-tip">开启后界面更加紧凑，适合小屏幕设备</span>
              </el-form-item>
            </el-form>
          </el-card>

          <!-- 通知设置 -->
          <el-card class="settings-card">
            <template #header>
              <div class="card-header">
                <el-icon><Bell /></el-icon>
                <span>通知设置</span>
              </div>
            </template>
            
            <el-form label-width="120px">
              <el-form-item label="桌面通知">
                <el-switch v-model="settings.notifications.enableDesktop" />
              </el-form-item>

              <el-form-item label="邮件通知">
                <el-switch v-model="settings.notifications.enableEmail" />
              </el-form-item>

              <el-form-item label="短信通知">
                <el-switch v-model="settings.notifications.enableSMS" />
              </el-form-item>

              <el-form-item label="免打扰">
                <el-switch v-model="settings.notifications.quietHours.enabled" />
                <div v-if="settings.notifications.quietHours.enabled" class="quiet-hours">
                  <el-time-picker
                    v-model="settings.notifications.quietHours.start"
                    placeholder="开始时间"
                    format="HH:mm"
                    style="width: 120px; margin-right: 10px;"
                  />
                  <span>至</span>
                  <el-time-picker
                    v-model="settings.notifications.quietHours.end"
                    placeholder="结束时间"
                    format="HH:mm"
                    style="width: 120px; margin-left: 10px;"
                  />
                </div>
              </el-form-item>

              <el-form-item label="通知类型">
                <div class="notification-types">
                  <el-checkbox v-model="settings.notifications.types.system">
                    系统通知
                  </el-checkbox>
                  <el-checkbox v-model="settings.notifications.types.security">
                    安全通知
                  </el-checkbox>
                  <el-checkbox v-model="settings.notifications.types.updates">
                    更新通知
                  </el-checkbox>
                  <el-checkbox v-model="settings.notifications.types.marketing">
                    营销通知
                  </el-checkbox>
                </div>
              </el-form-item>
            </el-form>
          </el-card>

          <!-- 安全设置 -->
          <el-card class="settings-card">
            <template #header>
              <div class="card-header">
                <el-icon><Lock /></el-icon>
                <span>安全设置</span>
              </div>
            </template>
            
            <el-form label-width="120px">
              <el-form-item label="自动登出">
                <el-switch v-model="settings.security.autoLogout" />
                <el-input-number
                  v-if="settings.security.autoLogout"
                  v-model="settings.security.autoLogoutTime"
                  :min="5"
                  :max="240"
                  style="margin-left: 10px; width: 120px;"
                />
                <span v-if="settings.security.autoLogout" class="form-tip">分钟</span>
              </el-form-item>

              <el-form-item label="双因子认证">
                <el-switch v-model="settings.security.twoFactorAuth" />
                <span class="form-tip">增强账户安全性</span>
              </el-form-item>

              <el-form-item label="登录通知">
                <el-switch v-model="settings.security.loginNotification" />
              </el-form-item>

              <el-form-item label="密码过期">
                <el-switch v-model="settings.security.passwordExpiry" />
                <el-input-number
                  v-if="settings.security.passwordExpiry"
                  v-model="settings.security.passwordExpiryDays"
                  :min="30"
                  :max="365"
                  style="margin-left: 10px; width: 120px;"
                />
                <span v-if="settings.security.passwordExpiry" class="form-tip">天</span>
              </el-form-item>
            </el-form>
          </el-card>

          <!-- 系统偏好 -->
          <el-card class="settings-card">
            <template #header>
              <div class="card-header">
                <el-icon><Setting /></el-icon>
                <span>系统偏好</span>
              </div>
            </template>
            
            <el-form label-width="120px">
              <el-form-item label="语言">
                <el-select v-model="settings.preferences.language" style="width: 200px;">
                  <el-option
                    v-for="option in languageOptions"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="时区">
                <el-select v-model="settings.preferences.timezone" style="width: 250px;">
                  <el-option
                    v-for="option in timezoneOptions"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="日期格式">
                <el-radio-group v-model="settings.preferences.dateFormat">
                  <el-radio value="YYYY-MM-DD">2024-08-22</el-radio>
                  <el-radio value="MM/DD/YYYY">08/22/2024</el-radio>
                  <el-radio value="DD/MM/YYYY">22/08/2024</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="时间格式">
                <el-radio-group v-model="settings.preferences.timeFormat">
                  <el-radio value="24h">24小时制</el-radio>
                  <el-radio value="12h">12小时制</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="分页大小">
                <el-select v-model="settings.preferences.pageSize" style="width: 120px;">
                  <el-option label="10" :value="10" />
                  <el-option label="20" :value="20" />
                  <el-option label="50" :value="50" />
                  <el-option label="100" :value="100" />
                </el-select>
              </el-form-item>
            </el-form>
          </el-card>
        </div>
      </el-col>

      <el-col :lg="8" :md="24">
        <div class="settings-sidebar">
          <!-- 数据管理 -->
          <el-card class="action-card">
            <template #header>
              <div class="card-header">
                <el-icon><Download /></el-icon>
                <span>数据管理</span>
              </div>
            </template>
            
            <div class="action-buttons">
              <el-button
                type="primary"
                :loading="backupLoading"
                @click="backupData"
                style="width: 100%; margin-bottom: 12px;"
              >
                <el-icon><Download /></el-icon>
                备份数据
              </el-button>

              <el-button
                type="success"
                :loading="exportLoading"
                @click="exportSettings"
                style="width: 100%; margin-bottom: 12px;"
              >
                <el-icon><Upload /></el-icon>
                导出设置
              </el-button>

              <el-button
                type="warning"
                @click="clearCache"
                style="width: 100%; margin-bottom: 12px;"
              >
                <el-icon><Delete /></el-icon>
                清除缓存
              </el-button>

              <el-button
                type="danger"
                @click="resetSettings"
                style="width: 100%;"
              >
                <el-icon><Refresh /></el-icon>
                重置设置
              </el-button>
            </div>

            <el-divider />

            <div class="backup-info">
              <h4>自动备份</h4>
              <el-form label-width="80px" size="small">
                <el-form-item label="启用">
                  <el-switch v-model="settings.data.autoBackup" />
                </el-form-item>
                <el-form-item label="频率">
                  <el-select v-model="settings.data.backupFrequency" style="width: 100%;">
                    <el-option label="每日" value="daily" />
                    <el-option label="每周" value="weekly" />
                    <el-option label="每月" value="monthly" />
                  </el-select>
                </el-form-item>
                <el-form-item label="保留天数">
                  <el-input-number
                    v-model="settings.data.retentionDays"
                    :min="7"
                    :max="365"
                    style="width: 100%;"
                  />
                </el-form-item>
              </el-form>
            </div>
          </el-card>

          <!-- 系统信息 -->
          <el-card class="info-card">
            <template #header>
              <div class="card-header">
                <el-icon><Monitor /></el-icon>
                <span>系统信息</span>
              </div>
            </template>
            
            <div class="system-info">
              <div class="info-item">
                <span class="label">版本:</span>
                <span class="value">v1.0.0</span>
              </div>
              <div class="info-item">
                <span class="label">构建时间:</span>
                <span class="value">2024-08-22</span>
              </div>
              <div class="info-item">
                <span class="label">浏览器:</span>
                <span class="value">Chrome 126.0</span>
              </div>
              <div class="info-item">
                <span class="label">操作系统:</span>
                <span class="value">Windows 11</span>
              </div>
            </div>
          </el-card>
        </div>
      </el-col>
    </el-row>

    <!-- 底部操作栏 -->
    <div class="settings-footer">
      <el-button size="large" @click="$router.go(-1)">
        取消
      </el-button>
      <el-button
        type="primary"
        size="large"
        :loading="loading"
        @click="saveSettings"
      >
        保存设置
      </el-button>
    </div>
  </div>
</template>

<style scoped lang="scss">
.settings-container {
  padding: 24px;
  background: transparent;
  min-height: calc(100vh - 64px);
  
  .settings-header {
    margin-bottom: 32px;
    
    h1 {
      font-size: 28px;
      font-weight: 700;
      color: #1e293b;
      margin: 0 0 8px 0;
      letter-spacing: -0.025em;
    }
    
    p {
      color: #64748b;
      font-size: 16px;
      margin: 0;
    }
  }
  
  .el-card {
    border-radius: 16px;
    border: 1px solid rgba(226, 232, 240, 0.8);
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05), 0 1px 20px rgba(0, 0, 0, 0.04);
    overflow: hidden;
    
    :deep(.el-card__header) {
      background: #f8fafc;
      border-bottom: 1px solid #e2e8f0;
      padding: 24px;
      
      .card-header {
        display: flex;
        align-items: center;
        gap: 12px;
        font-weight: 600;
        color: #1e293b;
        font-size: 18px;
        
        .el-icon {
          font-size: 20px;
          color: #3b82f6;
        }
      }
    }

    :deep(.el-card__body) {
      padding: 32px;
    }
  }
  
  .settings-content {
    .settings-card {
      margin-bottom: 24px;
      
      .el-form {
        .el-form-item {
          margin-bottom: 32px;

          :deep(.el-form-item__label) {
            font-weight: 600;
            color: #374151;
            margin-bottom: 12px;
            font-size: 14px;
          }
          
          .form-tip {
            color: #64748b;
            font-size: 12px;
            margin-left: 8px;
            font-style: italic;
          }
        }
      }
      
      .color-picker-group {
        display: flex;
        gap: 12px;
        flex-wrap: wrap;
        
        .color-option {
          width: 40px;
          height: 40px;
          border-radius: 8px;
          cursor: pointer;
          border: 2px solid transparent;
          display: flex;
          align-items: center;
          justify-content: center;
          transition: all 0.3s ease;
          position: relative;
          
          &:hover {
            transform: scale(1.1);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
          }
          
          &.active {
            border-color: #fff;
            box-shadow: 0 0 0 2px #3b82f6, 0 4px 12px rgba(59, 130, 246, 0.3);
          }
          
          .el-icon {
            color: white;
            font-size: 18px;
            filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.3));
          }
        }
      }
      
      .quiet-hours {
        margin-top: 12px;
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 16px;
        background: #f8fafc;
        border-radius: 8px;
        border: 1px solid #e2e8f0;

        span {
          color: #374151;
          font-weight: 500;
        }
        
        .el-time-picker {
          :deep(.el-input__wrapper) {
            border-radius: 6px;
          }
        }
      }
      
      .notification-types {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 16px;
        
        .el-checkbox {
          padding: 12px 16px;
          background: #f8fafc;
          border-radius: 8px;
          border: 1px solid #e2e8f0;
          transition: all 0.3s ease;
          
          &:hover {
            border-color: #3b82f6;
            background: #eff6ff;
          }

          :deep(.el-checkbox__label) {
            font-weight: 500;
            color: #374151;
          }

          &.is-checked {
            background: #eff6ff;
            border-color: #3b82f6;
          }
        }
      }

      .el-radio-group {
        display: flex;
        gap: 20px;
        flex-wrap: wrap;
        
        .el-radio {
          margin-right: 0;
          
          :deep(.el-radio__label) {
            font-weight: 500;
            color: #374151;
          }

          &.is-checked {
            :deep(.el-radio__label) {
              color: #3b82f6;
            }
          }
        }

        .el-radio-button {
          :deep(.el-radio-button__inner) {
            border-radius: 8px;
            margin: 0 4px;
            font-weight: 500;
            padding: 8px 16px;
            display: flex;
            align-items: center;
            gap: 6px;
            
            .el-icon {
              font-size: 16px;
            }
          }

          &.is-active {
            :deep(.el-radio-button__inner) {
              background: #3b82f6;
              border-color: #3b82f6;
              color: white;
            }
          }
        }
      }

      .el-switch {
        :deep(.el-switch__core) {
          border-radius: 12px;
          height: 24px;
          
          &::after {
            width: 20px;
            height: 20px;
          }
        }
      }

      .el-input-number {
        :deep(.el-input__wrapper) {
          border-radius: 8px;
        }
      }

      .el-select {
        :deep(.el-input__wrapper) {
          border-radius: 8px;
        }
      }
    }
  }
  
  .settings-sidebar {
    .action-card,
    .info-card {
      margin-bottom: 24px;
      
      .action-buttons {
        display: flex;
        flex-direction: column;
        gap: 12px;
        
        .el-button {
          border-radius: 8px;
          font-weight: 500;
          padding: 12px 20px;
          justify-content: flex-start;
          
          .el-icon {
            margin-right: 8px;
            font-size: 16px;
          }

          &.el-button--primary {
            background: linear-gradient(135deg, #3b82f6, #1d4ed8);
            border: none;
          }

          &.el-button--success {
            background: linear-gradient(135deg, #10b981, #059669);
            border: none;
          }

          &.el-button--warning {
            background: linear-gradient(135deg, #f59e0b, #d97706);
            border: none;
          }

          &.el-button--danger {
            background: linear-gradient(135deg, #ef4444, #dc2626);
            border: none;
          }
        }
      }
      
      .backup-info {
        margin-top: 24px;
        padding-top: 24px;
        border-top: 1px solid #e2e8f0;
        
        h4 {
          margin: 0 0 20px 0;
          color: #1e293b;
          font-size: 16px;
          font-weight: 600;
        }

        .el-form {
          .el-form-item {
            margin-bottom: 20px;

            :deep(.el-form-item__label) {
              font-weight: 500;
              color: #374151;
              font-size: 13px;
            }
          }
        }
      }
      
      .system-info {
        .info-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 12px 0;
          border-bottom: 1px solid #f1f5f9;
          
          &:last-child {
            border-bottom: none;
          }
          
          .label {
            color: #64748b;
            font-size: 14px;
            font-weight: 500;
          }
          
          .value {
            color: #1e293b;
            font-size: 14px;
            font-weight: 600;
            font-family: 'SF Mono', Consolas, monospace;
          }
        }
      }
    }
  }
  
  .settings-footer {
    margin-top: 40px;
    padding: 24px 0;
    border-top: 1px solid #e2e8f0;
    display: flex;
    justify-content: flex-end;
    gap: 16px;
    
    .el-button {
      border-radius: 8px;
      font-weight: 600;
      padding: 12px 32px;
      font-size: 14px;
      
      &.el-button--primary {
        background: linear-gradient(135deg, #3b82f6, #1d4ed8);
        border: none;
        
        &:hover {
          background: linear-gradient(135deg, #2563eb, #1e40af);
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .settings-container {
    .settings-sidebar {
      margin-top: 24px;
    }
  }
}

@media (max-width: 768px) {
  .settings-container {
    padding: 16px;

    .settings-header {
      h1 {
        font-size: 24px;
      }
    }

    .el-card {
      :deep(.el-card__header) {
        padding: 20px;
      }

      :deep(.el-card__body) {
        padding: 24px;
      }
    }
    
    .settings-content {
      .settings-card {
        .color-picker-group {
          justify-content: center;
        }

        .quiet-hours {
          flex-direction: column;
          align-items: stretch;
          gap: 8px;
          
          .el-time-picker {
            width: 100%;
          }
        }

        .notification-types {
          grid-template-columns: 1fr;
        }

        .el-radio-group {
          .el-radio-button {
            flex: 1;
            
            :deep(.el-radio-button__inner) {
              width: 100%;
              justify-content: center;
            }
          }
        }
      }
    }
    
    .settings-footer {
      flex-direction: column;
      
      .el-button {
        width: 100%;
        justify-content: center;
      }
    }
  }
}
</style>